//
//  ViewController.swift
//  NoteBook
//
//  Created by iOS Developer on 2017/4/25.
//  Copyright © 2017年 sunsheen. All rights reserved.
//

import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var keyInput: UITextField!
    
    @IBOutlet weak var login: UIButton!
    @IBOutlet weak var imgBackground: UIImageView!
    var effectView: UIVisualEffectView!
    override func viewDidLoad() {
        super.viewDidLoad()
        keyInput.delegate = self
        login.layer.cornerRadius = 5
        
        effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        effectView.frame = imgBackground.frame
        effectView.alpha = 0.7
        imgBackground.addSubview(effectView)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NSLog(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!)
    }
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    @IBAction func loginNoteBook(_ sender: Any) {
        //check wether input some key
        keyInput.endEditing(true)
        var keyValue: String = keyInput.text ?? ""
        keyValue = keyValue.replacingOccurrences(of: " ", with: "")
        guard !keyValue.isEmpty else {
            let alert = UIAlertController(title: "提示", message: "请输入点什么", preferredStyle: .alert)
            present(alert, animated: true){
                alert.dismiss(animated: true) {
                    self.keyInput.becomeFirstResponder()
                }
            }
            return
        }
        keyInput.text = ""
        keyValue = keyValue.md5()
        let fetch: NSFetchRequest<Writer> = Writer.fetchRequest()
        fetch.predicate = NSPredicate(format: "name = %@", keyValue)
        if let result = try? AppDelegate.viewContext.fetch(fetch) {
            if result.count > 0 {
                assert(result.count == 1, "there has more one book has the same key")
                AppDelegate.currentWriter = result[0]
                performSegue(withIdentifier: "login", sender: nil)
            }else {
                // no book, need create a new writer
                let writer = Writer(context: AppDelegate.viewContext)
                writer.name = keyValue
                do {
                    try AppDelegate.viewContext.save()
                }catch {
                    NSLog("save new writer exception \(error.localizedDescription)")
                }
                AppDelegate.currentWriter = writer
                performSegue(withIdentifier: "login", sender: nil)
            }
        }
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyInput.endEditing(true)
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
            self.effectView.alpha = 1
        }
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
            self.effectView.alpha = 0.7
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        keyInput.endEditing(true)
    }

    @IBAction func close(segue:UIStoryboardSegue){ }

}

